#include "include/ltgsql.h"
#include <stdarg.h>
#include <time.h>

static ltgsql_log_level current_log_level = LTGSQL_LOG_INFO;

void ltgsql_set_log_level(ltgsql_log_level level) {
    current_log_level = level;
}

void ltgsql_log(ltgsql_log_level level, const char* format, ...) {
    if (level < current_log_level) return;

    const char* level_str[] = {
        "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"
    };

    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    char timestamp[20];
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_info);

    // 输出到stderr
    fprintf(stderr, "%s [LTGSQL-%s] ", timestamp, level_str[level]);

    va_list args;
    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);

    fprintf(stderr, "\n");

    // 如果需要，也输出到文件
#ifdef LTGSQL_LOG_TO_FILE
    FILE* log_file = fopen("ltgsql.log", "a");
    if (log_file) {
        fprintf(log_file, "%s [LTGSQL-%s] ", timestamp, level_str[level]);
        va_start(args, format);
        vfprintf(log_file, format, args);
        va_end(args);
        fprintf(log_file, "\n");
        fclose(log_file);
    }
#endif

    if (level == LTGSQL_LOG_FATAL) {
        abort();
    }
}